package net.sxjr.protal.publicservice;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.sxjr.common.FengKongEnum;
import net.sxjr.mbg.entity.IgRemindObjectManage;
import net.sxjr.mbg.entity.IgSmsManage;
import net.sxjr.mbg.mapper.IgRemindObjectManageMapper;
import net.sxjr.protal.mapper.LoginMapper;
import net.sxjr.protal.mapper.SmsManageMapper;
import net.sxjr.protal.user.dao.LoginUserInfo;
import net.sxjr.protal.user.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：cuixc
 * @date ：Created in 2020/12/15 14:01
 * @description：公共问题 处理类
 * @modified By：
 */
@Slf4j
@Service
public class PublicService {

    @Autowired
    private LoginMapper loginMapper;
    //当前环节处理 link_confirm
    @Autowired
    private LoginService loginService;
    @Autowired
    private SmsManageMapper smsManageMapper;
    @Autowired
    private IgRemindObjectManageMapper remindObjectManageMapper;//提醒人



    //消息平台 消息 写入  环节编码  监督编码  发送人
    @Async
    public void writeSmsManage(String linkCode,String supervise){
        if(StringUtils.isBlank(linkCode) || StringUtils.isBlank(supervise)) {
            return;
        }

        List<SmsWriteContent> writeSmsContent = smsManageMapper.getWriteSmsContent(linkCode);
        if(writeSmsContent == null || writeSmsContent.size() == 0) return;
        String remindObjectId = writeSmsContent.get(0).getRemindObjectId();
        if(StringUtils.isBlank(remindObjectId)) return;
        String[] split = remindObjectId.split(",");
        for (String s : split) {
            IgRemindObjectManage igRemindObjectManage = remindObjectManageMapper.selectById(s);
            if(igRemindObjectManage == null) continue;
            //写入消息信息
            IgSmsManage smsManage = new IgSmsManage();
            smsManage.setSmsType(writeSmsContent.get(0).getSupervisionTypeName());
            smsManage.setSmsCode(loginMapper.superviseCode("SMS_CODE"));
            smsManage.setSmsContent(writeSmsContent.stream().map(r -> r.getPreventiveMeasures()).collect(Collectors.joining()));
            smsManage.setPhone(igRemindObjectManage.getPhone());
            smsManage.setRemindObjectId(igRemindObjectManage.getRemindObjectId());
            smsManage.setRemindLink(linkCode);
            smsManage.setSuperviseCode(supervise);
            smsManage.insert();

        }

    }



    @Async
    public <T> void setLinkConfirm(T t, LoginUserInfo currentUser){
        try {
            Class<?> tClass = t.getClass();


            Field f = tClass.getDeclaredField("currentLink");
            f.setAccessible(true);
            String currentLink = (String) f.get(t);
            if(currentLink == null) return;
            //环节编号 尾数  linkConfirmOp linkConfirmDate
            currentLink = currentLink.trim();
            String index = currentLink.substring(currentLink.length() - 2, currentLink.length());
            if(index.startsWith("0")){
                index = currentLink.substring(currentLink.length() - 1, currentLink.length());
            }
            Field[] declaredFields = tClass.getDeclaredFields();
            String nn = "linkConfirmOp"+index;
            long count = Arrays.stream(declaredFields).filter(v -> v.getName().equals(nn)).count();
            if(count ==0) return;
            Field op = tClass.getDeclaredField(nn);
            op.setAccessible(true);
            op.set(t,currentUser.getUserName());

            Field da = tClass.getDeclaredField("linkConfirmDate"+index);
            da.setAccessible(true);
            da.set(t,new Date());

            Method updateById = tClass.getMethod("updateById");
            updateById.invoke(t);
        }catch (Exception e){
            log.error("处理当前环节处理人 失败 {} {} ", JSON.toJSONString(t),e.getMessage());
        }
    }


    //  根据项目id  判断 项目所属类别
    public FengKongEnum getProject(String projectId) throws Exception {
        FengKongEnum[] values = FengKongEnum.values();
        for (FengKongEnum value : values) {
            Class<?> name = Class.forName(value.getClassType());
            Object o = name.newInstance();
            Field op = name.getDeclaredField(value.getClassId());
            op.setAccessible(true);
            op.set(o,projectId);

            Method updateById = name.getMethod("selectById");
            Object invoke = updateById.invoke(o);
            if(invoke != null){
                return value;
            }
        }
        return null;

    }

    //  根据项目环节 判断下个环节
    public <T> String getLinkCode(T t) {
        try{
            Class<?> tClass = t.getClass();


            Field f = tClass.getDeclaredField("currentLink");
            f.setAccessible(true);
            String currentLink = (String) f.get(t);
            if(StringUtils.isBlank(currentLink)) {
                FengKongEnum[] values = FengKongEnum.values();
                for (FengKongEnum value : values) {
                    String classType = tClass.getTypeName();
                    if(value.getClassType().equals(classType)){
                        return value.getLinkCode();
                    }
                }
            }

            Long value = Long.valueOf(currentLink);
            value += 1;
            return value+"";

        }catch (Exception e){
            log.error("处理环节失败 {}",JSON.toJSONString(t));
        }
        return null;

    }

    // 把一个字符串的第一个字母大写、效率是最高的、
    private static String getMethodName(String fildeName) throws Exception{
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
